﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace NetworkSupervisor.Helper
{
    /// <summary>
    /// DES加密、解密类
    /// </summary>
    public class DESEncryptHelper
    {
        /// <summary>
        /// 默认密钥，默认值为"sayakame"
        /// </summary>
        private const string DefaultKey = "sayakame";

        /// <summary>
        /// 用DES加密字符串
        /// </summary>
        /// <param name="inputString">要加密的字符串</param>
        /// <param name="Key">密钥，默认值为"sayakame"</param>
        /// <returns>通过DES加密后的字符串</returns>
        public static string Encrypt(string inputString, string Key = DefaultKey)
        {
            Key = Key + "00000000"; //保证Key至少为8位
            DESCryptoServiceProvider key = new DESCryptoServiceProvider();
            byte[] rgbKey = ASCIIEncoding.UTF8.GetBytes(Key.Substring(0, 8));
            key.Key = key.IV = rgbKey;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cs);
            sw.WriteLine(inputString);
            sw.Close();
            cs.Close();
            byte[] buffer = ms.ToArray();
            ms.Close();
            key.Dispose();
            return Convert.ToBase64String(buffer);
        }

        /// <summary>
        /// 用DES解密字符串
        /// </summary>
        /// <param name="inputString">要解密的字符串</param>
        /// <param name="Key">密钥，默认值为"sayakame"</param>
        /// <returns>通过DES解密后的字符串</returns>
        public static string Decrypt(string inputString, string Key = DefaultKey)
        {
            Key = Key + "00000000"; //保证Key至少为8位
            DESCryptoServiceProvider key = new DESCryptoServiceProvider();
            byte[] rgbKey = ASCIIEncoding.UTF8.GetBytes(Key.Substring(0, 8));
            key.Key = key.IV = rgbKey;
            MemoryStream ms = new MemoryStream(Convert.FromBase64String(inputString));
            CryptoStream cs = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            string val = sr.ReadLine();
            sr.Close();
            cs.Close();
            ms.Close();
            key.Dispose();
            return val;
        }
    }
}